﻿using HslCommunication;
using HslCommunication.Profinet.Siemens;

namespace PLCComponent;

public class HslCommunicationHelper
{
    private SiemensS7Net currentPlc;

    public void GetConnection()
    {
        try
        {
            SiemensS7Net plc = Connect("10.10.10.100", 0, 1);
            currentPlc = plc;
            bool var = ReadBool("DB1.DBX0.0");
            Console.WriteLine(var);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
    
    public SiemensS7Net Connect(string IP, byte Rack, byte Slot)
    {
        // 1. 创建 Siemens PLC 对象（以 S7-1500 为例）
        SiemensS7Net plc = new SiemensS7Net(SiemensPLCS.S1500)
        {
            IpAddress = IP, // 替换为你的 PLC IP 地址
            Rack = Rack,
            Slot = Slot
        };
        // 2. 打开连接
        OperateResult connectResult = plc.ConnectServer();
        if (!connectResult.IsSuccess)
        {
            Console.WriteLine($"连接失败: {connectResult.Message}");
            throw new Exception(connectResult.Message);
        }
        // finally
        // {
        //     // 5. 关闭连接
        //     plc.ConnectClose();
        //     Console.WriteLine("已断开 PLC 连接");
        // }
        Console.WriteLine("PLC 连接成功！");
        return plc;
    }

    public bool ReadBool(string address)
    { 
        OperateResult<bool> result = currentPlc.ReadBool(address);
        return result.Content;
    }
}